package com.spring.boot.standard.admin.controller;

import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.spring.boot.standard.admin.entity.Developerconfiguration;
import com.spring.boot.standard.admin.service.DeveloperconfigurationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import com.spring.boot.standard.admin.common.beans.PageData;
import com.spring.boot.standard.admin.common.CommonController;
import com.spring.boot.standard.admin.common.beans.CommonResult;
import com.spring.boot.standard.admin.entity.User;
import com.spring.boot.standard.admin.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author qinhao
 * @since Fri Sep 03 08:07:51 UTC 2021
 */
@RestController
@RequestMapping("/user")
@Api(value="用户接口",tags={"user(用户)接口"})
public class UserController extends CommonController {
	
    @Autowired
    UserService userService;

	@Autowired
	DeveloperconfigurationService developerconfigurationService;

	@ApiOperation(value = "用户登录" ,notes = "用户登录" )
	@ApiImplicitParams({
			@ApiImplicitParam(name = "username",value = "用户名",required = true,dataType = "String"),
			@ApiImplicitParam(name = "password",value = "密码",required = true,dataType = "String"),
			@ApiImplicitParam(name = "projectname",value = "项目名",required = true,dataType = "String")
	})
	@RequestMapping(value = "/login", method = { RequestMethod.GET  })
	public CommonResult login(String username, String password, String projectname){
		if (StringUtils.isEmpty(username)){
			return new CommonResult(false,500,null,"登录失败,用户名不能为空");
		}
		User userForBase=userService.findByUsername(username);
		if(userForBase==null){
			return new CommonResult(false,500,null,"登录失败,用户不存在");
		}else {
			if (StringUtils.isEmpty(password)){
				return new CommonResult(false,500,null,"登录失败,密码不能为空");
			}else if (!userForBase.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))){
				return new CommonResult(false,500,null,"登录失败,密码错误");
			}else {
				Developerconfiguration developerconfiguration = developerconfigurationService.findByUseridAndProject(userForBase.getUserid(),projectname);
				if(developerconfiguration!=null){
					String token = userService.getToken(userForBase);
					Map<String, Object> map = new HashMap<>();
					map.put("token", token);
					map.put("user", userForBase);
					map.put("config", developerconfiguration);
					return new CommonResult(true,200,map,"登录成功");
				}else{
					return new CommonResult(false,500,null,"登录失败,项目不存在");
				}
			}
		}
	}

	@ApiOperation(value = "用户注册" ,notes = "用户注册" )
	@ApiImplicitParams({
			@ApiImplicitParam(name = "username",value = "用户名",required = true,dataType = "String"),
			@ApiImplicitParam(name = "password",value = "密码",required = true,dataType = "String")
	})
	@RequestMapping(value="/register", method = { RequestMethod.GET })
	public CommonResult register(String username, String password) throws Exception {
		CommonResult cr = new CommonResult(false,500,null,"");

		User user = userService.findByUsername(username);
		//用户名没输错则验证密码
		if(user == null) {
			String md5_password = DigestUtils.md5DigestAsHex(password.getBytes());
			user = new User(null, username, md5_password, new Timestamp(System.currentTimeMillis()));
			userService.save(user);
			cr.setOk(true);
			cr.setData(user);
			cr.setCode(200);
		}else{
			cr.setOk(false);
			cr.setCode(500);
			cr.setMsg("用户名已存在!");
		}
		return cr;
	}

	@ApiOperation(value = "获取分页数据" ,notes = "获取分页数据" )
	@ApiImplicitParams({
		@ApiImplicitParam(name = "key" ,value = "搜索关键字名称" , required = false, dataType = "String"),
		@ApiImplicitParam(name = "keywords" ,value = "搜索关键字内容" , required = false, dataType = "String")
	})
    @RequestMapping(value = "/pagedata", method = { RequestMethod.GET  })
    public PageData<User> pagedata(Pageable pageable,String key,String keywords){
        return convertPage(userService.findAll(pageable,new Object[]{key,keywords}));
    }

	@ApiOperation(value = "获取单条数据对象" ,notes = "获取单条数据对象")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query",name = "userid" ,value = "用户ID" , required = true, dataType = "String")
	})
	@RequestMapping(value = "/singledata" ,method = { RequestMethod.GET })
	public User singledata(String userid){
		return userService.findById(userid);
	}

	@ApiOperation(value = "删除用户", notes = "删除用户" )
		@ApiImplicitParams({ @ApiImplicitParam(name = "ids", value = "ID拼接的字符串", required = true, dataType = "String")
	})
	@RequestMapping(value = "/delete" ,method = { RequestMethod.DELETE})
	public CommonResult delete(String ids) {
		try {
			String[] id_array = ids.split(",");
			for(String userid:id_array){
				userService.deleteById(userid);
			}
			cr = new CommonResult(true,0,null,"删除成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cr;
	}

	@ApiOperation(value = "保存用户", notes = "保存用户,id列为空则为新增,不为空则为修改")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "User",value = "用户",required = false,dataType = "User")
	})
	@RequestMapping(value = "/save" ,method = { RequestMethod.POST })
	public CommonResult save(User user) {
		try {
			userService.save(user);
			cr = new CommonResult(true,0,null,"保存成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return   cr;
	}

	@ApiOperation(value = "导出数据", notes = "导出数据")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "key" ,value = "搜索关键字名称" , required = false, dataType = "String"),
		@ApiImplicitParam(name = "keywords" ,value = "搜索关键字内容" , required = false, dataType = "String")
	})
	@RequestMapping(value = "/exports", method = { RequestMethod.GET  })
	public ResponseEntity<byte[]> exports( Pageable pageable,String key,String keywords) {
		ResponseEntity<byte[]> entity = null;
	    String[] titleNameArray = {"用户名","密码","创建时间"};
		String[] fieldNameArray = {"username","password","createtime"};
		try {
			//根据条件获取数据
            List<User> data = userService.findAll(pageable,new Object[]{key,keywords}).getContent();
			//数据转换成流并导出
			InputStream is = super.exportExcelContent(data,titleNameArray,fieldNameArray);
			byte[] body = new byte[is.available()];
			is.read(body);
			HttpHeaders headers = new HttpHeaders();
			String exportFilename = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date()) + ".xls";
			headers.add("Content-Disposition", "attchement;filename=" + exportFilename);
			HttpStatus statusCode = HttpStatus.OK;
			entity = new ResponseEntity<byte[]>(body, headers, statusCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return entity;
	}

	@ApiOperation(value = "导入用户", notes = "导入用户")
    @RequestMapping(value = "/imports", method = { RequestMethod.POST })
	public CommonResult imports(@RequestParam("file") MultipartFile file) {
		int imp_num = 0;
		//如果文件不为空，写入上传路径
		try {
			if(!file.isEmpty()) {
				String[] fieldNameArray = {"username","password","createtime"};
				List<Map<String,String>> list = super.getExcelContent(file, fieldNameArray);
                imp_num =  userService.saveFromList(list);
				cr = new CommonResult(true,0,null,"导入成功，导入数据："+imp_num+"条！");
			} else {
				cr = new CommonResult(false,500,null,"文件上传失败！");
			}
		} catch (Exception e) {
			cr = new CommonResult(false,500,null,super.getPointOfException(e.getMessage()));
		}
		return  cr;
	}

	@RequestMapping(value = "/getprojects", method = { RequestMethod.GET  })
	@ApiOperation(value = "获取用户项目列表", notes = "获取用户项目列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "username" ,value = "用户名" , required = false, dataType = "String"),
			@ApiImplicitParam(name = "password" ,value = "密码" , required = false, dataType = "String")
	})
	public CommonResult getprojects( String username, String password) throws Exception {
		CommonResult cr = new CommonResult(false,500,null,"");

		User user = userService.findByUsername(username);
		//用户名没输错则验证密码
		if(user != null) {
			String userid = user.getUserid();
			String md5_password = DigestUtils.md5DigestAsHex(password.getBytes());
			//密码正确则检查项目是否已存在
			if(md5_password.equals(user.getPassword())){
				List<Developerconfiguration> list = developerconfigurationService.selectListByUserid(userid);
				cr.setOk(true);
				cr.setData(list);
				cr.setCode(200);
			}else{
				cr.setOk(false);
				cr.setCode(500);
				cr.setMsg("密码错误!");
			}
		}else{
			cr.setOk(false);
			cr.setCode(500);
			cr.setMsg("用户不存在!");
		}
		return cr;
	}


	@RequestMapping(value = "/list", method = { RequestMethod.GET  })
	@ApiOperation(value = "获取全部用户", notes = "获取全部用户")
	public List<User> list() {
		return userService.findList();
	}

	@RequestMapping(value = "/addproject", method = { RequestMethod.GET  })
	@ApiOperation(value = "添加项目", notes = "添加项目")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "username" ,value = "用户名" , required = false, dataType = "String"),
			@ApiImplicitParam(name = "password" ,value = "密码" , required = false, dataType = "String"),
			@ApiImplicitParam(name = "projectname" ,value = "项目名称" , required = false, dataType = "String")
	})
	public CommonResult addproject( String username, String password, String projectname) throws Exception {
		CommonResult cr = new CommonResult(false,500,null,"");

		User user = userService.findByUsername(username);
		//用户名没输错则验证密码
		if(user != null) {
			String userid = user.getUserid();
			String md5_password = DigestUtils.md5DigestAsHex(password.getBytes());
			//密码正确则检查项目是否已存在
			if(md5_password.equals(user.getPassword())){
				Developerconfiguration developerconfiguration = developerconfigurationService.findByUseridAndProject(userid,projectname);
				// 不存在才允许注册
				if(developerconfiguration == null) {
					Developerconfiguration dc = new Developerconfiguration();
					dc.setUserid(userid);
					dc.setProjectname(projectname);
					developerconfigurationService.save(dc);
					cr.setOk(true);
					cr.setData(user);
					cr.setCode(200);
				}else {
					cr.setOk(false);
					cr.setCode(500);
					cr.setMsg("项目已存在!");
				}
			}else{
				cr.setOk(false);
				cr.setCode(500);
				cr.setMsg("密码错误!");
			}
		}else{
			cr.setOk(false);
			cr.setCode(500);
			cr.setMsg("用户不存在!");
		}
		return cr;
	}

	@RequestMapping(value = "/delproject", method = { RequestMethod.GET  })
	@ApiOperation(value = "删除项目", notes = "删除项目")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "username" ,value = "用户名" , required = false, dataType = "String"),
			@ApiImplicitParam(name = "password" ,value = "密码" , required = false, dataType = "String"),
			@ApiImplicitParam(name = "projectname" ,value = "项目名称" , required = false, dataType = "String")
	})
	public CommonResult delproject( String username, String password, String projectname) throws Exception {
		CommonResult cr = new CommonResult(false,500,null,"");
		User user = userService.findByUsername(username);
		//用户名没输错则验证密码
		if(user != null) {
			String userid = user.getUserid();
			String md5_password = DigestUtils.md5DigestAsHex(password.getBytes());
			//密码正确则检查项目是否已存在
			if(md5_password.equals(user.getPassword())){
				Developerconfiguration developerconfiguration = developerconfigurationService.findByUseridAndProject(userid,projectname);
				// 不存在才允许注册
				if(developerconfiguration == null) {
					cr.setOk(false);
					cr.setCode(500);
					cr.setMsg("项目不存在!");
				}else {
					developerconfigurationService.deleteById(developerconfiguration.getDeveloperconfigurationid());
					cr.setOk(true);
					cr.setCode(200);
					cr.setMsg("删除成功!");
				}
			}else{
				cr.setOk(false);
				cr.setCode(500);
				cr.setMsg("密码错误!");
			}
		}else{
			cr.setOk(false);
			cr.setCode(500);
			cr.setMsg("用户不存在!");
		}
		return cr;
	}

}